import {
  LinRouter,
  disableLoading
} from 'lin-mizar';

import {
  LoginType
} from '../../lib/enum';
import { Auth } from '../../middleware/auth';
import { TokenValidator, NotEmptyValidator } from '../../validator/token';
import { AppUserDao } from '../../dao/app-user';
const appUserDto = new AppUserDao();

const tokenApi = new LinRouter({
  prefix: '/mini/token',
  module: '鉴权'
});

tokenApi.post('/', async ctx => {
  const v = await new TokenValidator().validate(ctx);
  let token;
  switch (v.get('body.type')) {
    case LoginType.USER_EMAIL:
      // token = await emailLogin(v.get('body.account'),
      //   v.get('body.secret'));
      break;
    case LoginType.USER_MINI_PROGRAM:
      token = await appUserDto.codeToToken(v.get('body.account'));
      break;
    case LoginType.ADMIN_EMAIL:
      break;
    default:
      throw new global.errs.ParameterException('没有相应的处理函数');
  }
  ctx.body = {
    token
  };
});

tokenApi.post('/verify', async ctx => {
  const v = await new NotEmptyValidator().validate(ctx);
  const result = Auth.verifyToken(v.get('body.token'));
  ctx.body = {
    isValid: result
  };
});

module.exports = { tokenApi, [disableLoading]: false };
